package com.syp.auth.export.support.springmvc;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.syp.auth.domain.ProcessResult;
import com.syp.auth.export.common.GeneralUserVo;
import com.syp.auth.export.common.TokenCooikeMaster;
import com.syp.auth.export.resource.AuthorizeResourceI;
import com.syp.auth.export.util.CurrentUserHolder;
import com.syp.auth.export.util.RequestExcluder;
import com.syp.auth.export.util.SecurityExcluder;

import lombok.Setter;

public class SecurityInterceptor implements HandlerInterceptor {

	@Setter
	private AuthorizeResourceI authorizeResource;
	@Setter
	private String[] excludeUriPatterns;

	/**
	 * 在调用controller具体方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (SecurityExcluder.process(request, handler, excludeUriPatterns)) {
			return true;
		}

		Cookie token = TokenCooikeMaster.getInstunce().get(request);
		GeneralUserVo cuser = this.authorizeResource.cuser(token.getValue());
		CurrentUserHolder.set(cuser);

		List<String> urlsList = cuser.getPermitUrlList();
		String url = RequestExcluder.takeOffContextPath(request);
		if (urlsList == null || !urlsList.contains(url)) {
			ProcessResult pr = new ProcessResult();
			pr.setSuccess(false);
			pr.setMsg("您没有访问此资源[" + url + "]的权限！请联系管理员！");

			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(JSON.toJSONString(pr));
			return false;
		}

		return true;
	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 完成页面的render后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}
}
